package Threadtest;

public class test9_volatile {


    public static void main(String[] args) throws InterruptedException {
        Task task=new Task();
        Thread t1=new Thread(task,"线程t1");

        Thread t2=new Thread(()->{
            try {
                Thread.sleep(1000);
                System.out.println("通知线程停止");
                task.stop=true;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"线程2");
        t1.start();
        t2.start();
        Thread.sleep(1000);
    }

}
class Task implements Runnable{
    int i=0;
    //volatile确保数据可见性,使用了底层的窥探技术
   volatile boolean stop=false;
    @Override
    public void run() {
        long s=System.currentTimeMillis();
        while (!stop){
            i++;
        }
        System.out.println("线程退出"+(System.currentTimeMillis()-s));
    }
}
